import GameObject from "./GameObject";
import Utils from "./utils"
import GameConst from "./GameConst";
import SoundsManager from "./soundmanager";
import BitmapText from "./BitmapText";
import ClickableObject from "./ClickableObject";
import Tips from "./tips";
export default class Hud extends GameObject {

    constructor() {
        super();
        var t = this;
        
        this.currentPercent = 0;
        this.barScale = .9;
        this.currentMoves = -1;
        this.currentTarget = "";
        this.currentScore = 0;
        this.stars = [];
        
        this.starsEarned = [false, false, false];
        
        var container = new Laya.Sprite;
        this.sprite = container;
        this.tips = [];


        Utils.addChild(this.sprite, GameConst.level.hudLayer);
        // var resArr = ["border_down", "border_top", "border_left", "border_right", "border"];
        // var posions = [Utils.cjp(0, 835), Utils.cjp(0, 0), Utils.cjp(0, 103), Utils.cjp(GameConst.SCREEN_W+2, 103), Utils.cjp(0, 0)];
        // var pivots = [Utils.cjp(0, 58), Utils.cjp(0, 0), Utils.cjp(0, 0), Utils.cjp(35, 0), Utils.cjp(0, 0)];
        // for (var i = 0; i < 4; ++i) {
        //     var a = Utils.createBitmap(resArr[i]);
        //     a.x = posions[i].x;
        //     a.y = posions[i].y + GameConst.SHIFT_H;
        //     a.pivotX = pivots[i].x;
        //     a.pivotY = pivots[i].y;
        //     container.addChild(a);
        // }


        var img = new Laya.Image('game/top.png');
        img.width = GameConst.SCREEN_W;
        img.sizeGrid = "4,4,4,4,1";
        img.y = GameConst.SHIFT_GAME-434;
        container.addChild(img);

        this.topImg = img;

        img = new Laya.Image('game/down.png');
        img.sizeGrid = "4,4,4,4,1";
        img.width = GameConst.SCREEN_W;
        img.y = GameConst.SHIFT_GAME+730;
        img.height = GameConst.FULL_SCREEN_H-img.y;
        container.addChild(img);
        this.downImg = img;

        var json = Laya.loader.getRes('prefabs/topui.json');
        var prefabs = new Laya.Prefab();
        prefabs.json = json;
        var ui = prefabs.create();
        container.addChild(ui);

        var scoreTextCtl = ui.getChildByName('score');

        // var bar = Utils.createBitmap("bar");
        // // bar.sizeGrid = "5,5,5,5";

        // Utils.addChild(bar, container);
        
        // this.bar = bar;
        // bar.x = 326 + 78 - 7 - 25 + 27 - 5 - 2;
        // bar.y = -5 + GameConst.SHIFT_H + 5 + 15 + 2 - 2;
        // bar.scaleX = bar.scaleY = this.barScale;

        var textLabel = new BitmapText("xxx",'game/');
        textLabel.letterSpacing = 1;
        textLabel.name= "movesText";
        this.movesText = textLabel;
        ui.getChildByName('moveleft').addChild(this.movesText);

        this.insect = ui.getChildByName('insect');
        this.starPos = [Utils.cjp(this.insect.x,this.insect.y)];
        for(var i=1;i<4;i++){
            var star = ui.getChildByName('star'+i);
            this.stars.push(star);
            var p = Utils.cjp(star.x,star.y);
            this.starPos.push(p);
        }

        var textLabel = new BitmapText("1","game/z_");
        textLabel.letterSpacing = -1;
        textLabel.name = "targetText";
        textLabel.x = GameConst.SCREEN_W/2+10;
        textLabel.y = 80;
        this.targetText = textLabel;
        ui.addChild(this.targetText);

        var textLabel = new BitmapText("0","game/");
        textLabel.letterSpacing = 1;
        textLabel.name="scoreText";
        this.scoreText = textLabel;
        scoreTextCtl.addChild(this.scoreText);
        this.scoreTextContainer = scoreTextCtl;
        // this.targetXText = textLabel;
        // container.addChild(this.targetXText);

        var img = new Laya.Sprite();
        img.x = GameConst.SCREEN_W/2;
        img.y = 110;
        ui.addChild(img);
        this.targetIcon = img;
        
        this.pauseButton = ui.getChildByName('btn_pause');
        this.pauseButton.on(Laya.Event.CLICK,this,this.pauseLevel);
        var clickObj = new ClickableObject(this.pauseButton);
		clickObj.setCircle(85, 0, 0);
		clickObj.callback = function () {
			t.pauseLevel()
        };

        this.clouds = [];
        for(var i=0;i<5;i++){
            var cloud = Utils.createSprite('game/cloud.png');
            if(i<2){
                this.topImg.addChild(cloud);
            }else{
                this.downImg.addChild(cloud);
            }
            this.randomClound(cloud,i);
            cloud.x = Utils.getInt(GameConst.SCREEN_W+cloud.width)-cloud.width;
            this.clouds.push(cloud);
        }

        
        //this.shuffleText = new BitmapText("reset","game/");
        // for (var i = 0; i < 2; ++i) {
        //     var textLabel = new BitmapText("触发reset特效");
        //     textLabel.text = i == 0 ? "no possible" : "moves!";
        //     textLabel.spaceWidth = 25;
        //     textLabel.letterSpacing = -10;
        //     textLabel.x = i == 0 ? -220 : -125;
        //     textLabel.y = i == 0 ? 0 : 65;
        //     this.shuffleText.addChild(textLabel);
        // }
        //this.update(0);

    }

    randomClound(cloud,i){
        var scale = (2+Utils.getInt(9))*0.1;
        cloud.scale(scale,scale,true);
        cloud.speed = Utils.getInt(15)+1;
        var randge = 434;
        var alphaMax = 0.8;
        if(i<2){
            randge = this.topImg.height-cloud.height;
        }else{
            randge = this.downImg.height;
            alphaMax = 0.5;
            
        }
        cloud.alpha = 0.2+(Math.random()*alphaMax);
        cloud.y = Utils.getInt(randge);
    }

    update(t) {
        
        // if(!this.barRect){
        //     this.barRect = this.bar.getBounds();
        //     for(var i=0;i<this.stars.length;i++){
        //         var img = this.stars[i];
        //         var x = this.bar.x -20;
        //         var x2 = this.bar.x + this.bar.displayWidth - 3;
        //         img.y = GameConst.SHIFT_H + 9 + img.pivotY;
        //         img.x = Utils.lerp(x, x2, this.starScales[i]);
        //     }

        //     var mask  = new Laya.Sprite();
        //     mask.pos(0,0);
        //     this.bar.mask = mask;
        // }
        super.update(t);
        if (GameConst.level && this.scores){
            this.updateBar(t);
        }
        if (GameConst.level.target && GameConst.level.target.isCompleted() && (!GameConst.level.target.isScoreTarget || GameConst.level.movesLeft <= 0)){
            var target = GameConst.level.target;
            GameConst.level.starMoveAwardMode();
        }

        for(var i=0;i<this.tips.length;i++){
            var tip = this.tips[i];
            if(tip.isDestroyed){
                this.tips.splice(i,1);
                break;
            }
            tip.update(t);
        }
        var n = GameConst.level.movesLeft;
        if (this.currentMoves != n) {
            Laya.Tween.clearAll(this.movesText);
            this.currentMoves = n;
            this.movesText.text = n.toString();
            this.movesText.scaleX = this.movesText.scaleY = .9;
            // var r = Utils.getTextSize(this.movesText);
            this.movesText.pivotX = this.movesText.getBounds().width / 2;
            this.movesText.scaleY = 1.5;
            Laya.Tween.to(this.movesText, {
                scaleY: 1
            }, 200, Laya.Ease.quadOut);
        }
        if (GameConst.level && GameConst.level.target) {
            var text = GameConst.level.target.getTargetText();
            if (text != this.currentTarget) {
                Laya.Tween.clearAll(this.targetText);
                this.currentTarget = text;
                this.targetText.text = text;
                var r = Utils.getTextSize(this.targetText);
                this.targetText.pivotX = 0;
                this.targetText.pivotY = r.y * 1.5;
                this.targetText.scaleY = 2;
                Laya.Tween.to(this.targetText,{
                    scaleY: 1
                }, 200, Laya.Ease.quadOut);
            }
        }
        var score = GameConst.level.score;
        if (this.currentScore < score) {
            Laya.Tween.clearAll(this.scoreText);
            this.currentScore = score;
            this.scoreText.text = score.toString();
            var r = Utils.getTextSize(this.scoreText);
            this.scoreText.pivotX = r.x / 2;
            this.scoreText.pivotY = r.y * 1.5;
            this.scoreText.x = 0;
            this.scoreText.y = 0 ;
            this.scoreText.scaleY = 1 * 2;
            Laya.Tween.to(this.scoreText,{
                scaleY: 1
            }, 200, Laya.Ease.quadOut);
            GameConst.adapter.freshMyScore(score);
        }
        for(i=0;i<this.clouds.length;i++){
            var cloud = this.clouds[i];
            var x = cloud.x;
            x += cloud.speed*t;
            if(x>GameConst.SCREEN_W){
                this.randomClound(cloud,i);
                x = -100-cloud.width;
            }
            cloud.x = x;
        }

    }


    updateBar(e) {

        var percent = GameConst.level.score / this.scores[3];
        percent = Utils.limit(percent, 0, 1);
        var move = percent - this.currentPercent;
        var speed = .005 * 60 * e;
        if (Math.abs(move) <= speed){
            this.currentPercent = percent;
        }else{
            this.currentPercent += speed * move / Math.abs(move);
        }
        var scoreLen = this.scores.length;
        var s = 1;
        var step = 1;
        for (var st=0; st < scoreLen; st++) {
            var p0 = this.scores[st-1] / this.scores[3];
            var p1 = this.scores[st] / this.scores[3];
            if (this.currentPercent >= p0 && this.currentPercent <= p1) {
                s = Utils.lerp(this.scores[st - 1], this.scores[st], (this.currentPercent - p0) / (p1 - p0))/this.scores[st];
                step = st;
                break
            }
        }
        var ip0 = this.starPos[step-1];
        var ip1 = this.starPos[step];
        this.insect.x = Utils.lerp(ip0.x,ip1.x,s);
        this.insect.y = Utils.lerp(ip0.y,ip1.y,s);
        //var w = Utils.limit(this.bar.width * s, 2, this.bar.width);
        // var mask = this.bar.mask;
        // mask.graphics.clear(true);
        // mask.graphics.drawRect(0,0,Math.floor(w),100,"#FF0000");
        var f = step - (this.currentPercent>=1?1:2);
        if (f >= 0 && !this.starsEarned[f]) {
            this.starsEarned[f] = true;
            this.stars[f].scaleY = 2;
            this.stars[f].scaleX = 2;
            Laya.Tween.to(this.stars[f], {
                scaleY: 1,
                scaleX: 1
            }, 400, Laya.Ease.quadOut);
        }
        for(var i=0;i<3;i++){
            if(this.starsEarned[i]){
                this.stars[i].rotation += 180*e%360;
            }
        }
    };

    show () {
        this.currentMoves = -1;
        this.currentTarget = "";
        this.currentScore = -1;
        this.currentPercent = 0;
        
        for (var e = 0; e < 3; ++e)
            this.starsEarned[e] = false;
        GameConst.level.needToUpdateBack = true;
        var score = GameConst.level.target.scores;
        this.scores = [0,score[0],score[1],score[2]];
        var t = GameConst.level.target.getText();
        this.targetIcon.loadImage("game/"+t[2]+".png");
        var bound = this.targetIcon.getBounds();
        var w = bound.width;
        if(w<70){
            w = 70;
        }
        this.targetIcon.pivotX = w;
        this.targetIcon.pivotY = w;
        this.targetIcon.scaleX = this.targetIcon.scaleY = 30 / w;
        this.update(0);

    
        var friends = GameConst.adapter.getFriends(GameConst.levelManager.currentLevel);
        if(friends){
            if(!this.toprank){
                this.toprank = new Laya.WXOpenDataViewer();
            }
            Utils.addChild(this.toprank, this.sprite);
            this.toprank.x = 0;
            this.toprank.y = GameConst.SHIFT_GAME+750;
            this.toprank.width = GameConst.SCREEN_W;
            this.toprank.height = 600;
        }else{
            GameConst.adapter.showAd();
        }


    };

    playShuffleAnimation () {
        this.playShuffle = Laya.timer.currTimer;
        new Tips('unbelievable',GameConst.SCREEN_W / 2,GameConst.SHIFT_H + 400);
    };


    isShuffleActive() {
        return this.playShuffle && Laya.timer.currTimer-this.playShuffle < 3000;
    };

    addTip(tip){
        this.sprite.addChild(tip.sprite);
        this.tips.push(tip);
    }
}

Hud.prototype.onDown = function (e, t) {

};
Hud.prototype.onHudUp = function (e, t) { };


Hud.prototype.pauseLevel = function () {
    if (GameConst.menuManager.target.sprite.parent || GameConst.level.isWaitingForTarget && !GameConst.level.isHardLocked || GameConst.menuManager.current == GameConst.menuManager.tutorial)
        return;
    GameConst.level.pause();
    SoundsManager.instance.playSound("pause");
};

Hud.prototype.forceFullUpdate = function () {
    this.updateBar(10);
    this.scoreText.text = GameConst.level.score.toString();
};
Object.defineProperty(Hud.prototype, "starEarnedAmount", {
    get: function () {
        var e = 0;
        for (var t = 0; t < 3; ++t)
            if (this.starsEarned[t])
                e++;
        return e;
    },
    enumerable: true,
    configurable: true
});


Hud.prototype.reset = function () {
    this.currentPercent = 0;
    Utils.removeClip(this.sprite);
    Utils.addChild(this.sprite, GameConst.level.hudLayer);
};
